//////////////////////////////////////////////////////////
var player_names = new Array();
var historyBoard = new Array();
var killsHistory = new Array();

for(var i=0;i<20;i++) {
	killsHistory[i] = new Array();
}

var players = new Array();
for(var i=0;i<20;i++) {
	players[players.length] = {name:"Player", num:99, num_pos:0, checked: false, ind:i};
	player_names[player_names.length] = 'Player'+i;
}

var canvas_killer;
var canvas_hurts;
var ctx_k;
var ctx_h;

var canvas_killer_offset;

//var player_nums = new Array();
var player_lifes = new Array();
var player_lifes_killed = new Array();

var players_max_count = 6;
var lifes_init_count = 8;
var dart_num_per_player = 3;
var killed_lifes_by_rad = new Array(0, 0, 1, 3, 1, 2);

var current_game_num = 1;
var current_round_num = 1;
var current_player = 0;
var current_dart_num = 1;
var extra_lifes_space_count = 7;

var last_blink_state = 0;
var prev_player;
var box_height;
var life_width;
var board_width;
var board_height;

//////////////////////////////////////////////////////////
function randomize_player_nums() {
	var next_num;
	var duplicated = 0;
	for (i=0; i<players_max_count; i++) {
//	if(players[i].checked) {
		 do {
			next_num = Math.floor(Math.random() * 20) + 1;

			var duplicated = 0;
			var fromlist = 1;
			for (j=0; j<i; j++) {
				//if (next_num == player_nums[j]) {
				if (next_num == players[j].num) {
					duplicated = 1;
					break;
				}
			}
//			if(selectedNums.length>0 && !selectedNums.inArray(next_num)) fromlist=0;
			if (!duplicated && fromlist) {break;}

		 } while (true);

		 //player_nums[i] = next_num;
		 players[i].num = next_num;

//	}
	}
}

Array.prototype.removeByIndex = function(index) {
    this.splice(index, 1);
}

function randomize_player_nums_choosen() {
	var next_num;
	var duplicated = 0;
	var tmpchoosen = selectedNums.slice();
	if(selectedNums.length>0) 
	for (i=0; i<players_max_count; i++) {
		if(players[i].checked) {
			next_num = Math.floor(Math.random() * (tmpchoosen.length));
			players[i].num = tmpchoosen[next_num];
//			console.log(next_num);console.log(tmpchoosen[next_num]);console.log(tmpchoosen);
			tmpchoosen.removeByIndex(next_num);
		} else players[i].num = 99;
	}

	for (i=0; i<players_max_count; i++) {
		if(players[i].num == 99) {
		 do {
			next_num = Math.floor(Math.random() * 20) + 1;

			var duplicated = 0;
			for (j=0; j<i; j++) {
				//if (next_num == player_nums[j]) {
				if (next_num == players[j].num) {
					duplicated = 1;
					break;
				}
			}
			if (!duplicated) {break;}

		 } while (true);

		 //player_nums[i] = next_num;
		 players[i].num = next_num;

		}
	}
}


//////////////////////////////////////////////////////////
function randomize_player_nums2() {
	var next_num, next_num_pos, neighbour1, neighbour2;
	var duplicated = 0;
  var neighbour = 0;
  var inf_loop_count = 0;

	for (i=0; i<players_max_count; i++) {
	if(players[i].checked) {
		 do {
			next_num_pos = Math.floor(Math.random() * 20);
		  next_num = nums[next_num_pos];

			duplicated = 0;
			for (j=0; j<i; j++) {
				if (next_num == players[j].num) {
					duplicated = 1;
					break;
				}
			}

			neighbour = 0;
			for (j=0; j<i; j++) {
        neighbour1 = next_num_pos-1;
        neighbour2 = next_num_pos+1;
        if (neighbour1<0) {
           neighbour1 = 19;
        }
        if (neighbour2>19) {
           neighbour2 = 0;
        }

				if ((players[j].num_pos == neighbour1) || (players[j].num_pos == neighbour2)) {
					neighbour = 1;
					break;
				}
			}

			if ((!duplicated) && (!neighbour)) {break;}
      inf_loop_count++;
      if (inf_loop_count > 200) {break;}

		 } while (true);

		 players[i].num = next_num;
		 players[i].num_pos = next_num_pos;

	}
	}
}
//////////////////////////////////////////////////////////
function randomize_player_nums3() {
	var next_num, next_num_pos, neighbor1, neighbor2;
	var duplicated = 0;
  var neighbor = 0;
	for (i=0; i<players_max_count; i++) {
	if(players[i].checked) {
		 do {

			next_num_pos = i*2;
		  next_num = nums[next_num_pos];

      break;

		 } while (true);

		 players[i].num = next_num;
		 players[i].num_pos = next_num_pos;

	}
	}
}
//////////////////////////////////////////////////////////
function randomize_player_nums4() {
	var next_num, next_num_pos, player1, player2, neighbour1, neighbour2;
	var duplicated = 0;
  var neighbour = 0;
  var inf_loop_count = 0;

  player1 = 0;//Math.floor(Math.random() * (players_max_count-1));
  next_num_pos = Math.floor(Math.random() * 10);
  players[player1].num_pos = next_num_pos;
  players[player1].num = nums[next_num_pos];

  player2 = 1//Math.floor(Math.random() * (players_max_count-1));
  next_num_pos = next_num_pos + 10;
  players[player2].num_pos = next_num_pos;
  players[player2].num = nums[next_num_pos];

//return;

	for (i=0; i<players_max_count-2; i++) {
	if ((players[i].checked) && (i!=player1) && (i!=player2)) {
		 do {
			next_num_pos = Math.floor(Math.random() * 20);
		  next_num = nums[next_num_pos];

			duplicated = 0;
			for (j=0; j<i; j++) {
				if (next_num == players[j].num) {
					duplicated = 1;
					break;
				}
			}

			neighbour = 0;
			for (j=0; j<i; j++) {
        neighbour1 = next_num_pos-1;
        neighbour2 = next_num_pos+1;
        if (neighbour1<0) {
           neighbour1 = 19;
        }
        if (neighbour2>19) {
           neighbour2 = 0;
        }

				if ((players[j].num_pos != neighbour1) && (players[j].num_pos != neighbour2)) {
					neighbour = 1;
					break;
				}
			}

			if ((!duplicated) && (!neighbour)) {break;}
      inf_loop_count++;
      if (inf_loop_count > 200) {break;}

		 } while (true);

		 players[i].num = next_num;
		 players[i].num_pos = next_num_pos;

	}
	}
}
//////////////////////////////////////////////////////////
function mysortfuntion(a,b) {
	return (a.num-b.num);
}
function sort_players() {
	players.sort(mysortfuntion);
}
//////////////////////////////////////////////////////////
function getPlayerNumChecked(id) {
	var num=0;
	for(var i=0;i<players.length;i++) {
		if(i == id) return num;
		if(players[i].checked) num++;
	}
}

function blink_curent_player() {
	if(gamestarted) {
   canvas = document.getElementById("darts_board");
   ctx = canvas.getContext("2d");
		ctx_k.save();
		ctx_k.fillStyle = "rgba(60,60,60,1)";
		var player_num = getPlayerNumChecked(current_player);
		ctx_k.fillRect(5, player_num*box_height+5, board_width-120*box_height/30, box_height-5*box_height/30);
		if (last_blink_state == 0) {
			ctx.fillStyle = ctx_k.fillStyle = "red";
			last_blink_state = 1;
		} else {
			ctx.fillStyle = ctx_k.fillStyle = "white";
			last_blink_state = 0;
		}
	   ctx.font = 30/350*darts_board_radius + "pt Arial";
		ctx_k.font = parseInt(18*box_height/30)+"pt Arial";
		//ctx_k.fillText(player_names[current_player] + " - " + current_dart_num, 10, current_player*box_height + 25);
		
		ctx_k.fillText(players[current_player].name + " - " + current_dart_num, 10, player_num*box_height + 30*box_height/30);
if((blind_rounds_count-current_round_num)<0) {
 var r = 372/350*darts_board_radius;
 var degree1;
 for (i=0; i<20; i=i+1) {
   degree1 = i * deg + deg;
   x1 = r * Math.cos( degree1 * Math.PI / 180);
   y1 = r * Math.sin( degree1 * Math.PI / 180);
   if(nums[i] == players[current_player].num) ctx.fillText(nums[i], cx+x1-(20/350*darts_board_radius), cy+y1+(15/350*darts_board_radius));
 }

}
   ctx.restore();
	



		ctx_k.restore();
	}
	setTimeout(blink_curent_player, 500);
}

//////////////////////////////////////////////////////////


function countAlivePlayers() {
	var count =0;
	for (var i=0; i<players_max_count; i++) {
		if((player_lifes[i]-player_lifes_killed[i])>0) count++;
	}
	return count;
}

function chooseSectors() {
	if(gamestarted && countAlivePlayers()>1) {
		if(confirm('Game is already started. Are you sure you want to start new game?')) {
			gamestarted = false;
			killer_draw_state();
		}
	}
}

function start_new_game(game_num,randomizer) {
	if(selectedNums.length>0 && selectedNums.length <countCheckedPlayers()) {
		alert('Count of players is greater than sectors count');
		return;
	} 
	if(gamestarted && countAlivePlayers()>1) {
		if(!confirm('Game is already started. Are you sure you want to start new game?')) {
			return;
		}
	}
	gamestarted = true;
	current_game_num = game_num;
	current_round_num = 1;
	current_player = 0;
	current_dart_num = 1;
	dartsArr = new Array();
	killsHistory = new Array();
	for(var i=0;i<20;i++) {
		killsHistory[i] = new Array();
	}

	// add initial lifes
	for (var i=0; i<players_max_count; i++) {
	 //players[i] = {name:"Player", num:99};
//	 players[i].name = player_names[i];
	 players[i].num = 99;
	 player_lifes[i] = lifes_init_count;
	 player_lifes_killed[i] = 0;
	}

	randomizer();
	sort_players();
	killer_draw_state();
	setHistoryBoard();
}
//////////////////////////////////////////////////////////
function findPos(obj) {
	 var curleft = curtop = 0;
	 if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			} while (obj = obj.offsetParent);
			return { x: curleft, y: curtop };
	 }
}
//////////////////////////////////////////////////////////
function draw_life(ctx, x, y, w, h) {
	var kappa = .5522848;
		ox = (w / 2) * kappa; // control point offset horizontal
		oy = (h / 2) * kappa; // control point offset vertical
		xe = x + w;				// x-end
		ye = y + h;				// y-end
		xm = x + w / 2;		 // x-middle
		ym = y + h / 2;		 // y-middle

	ctx.beginPath();
	ctx.moveTo(x, ym);
	ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
	ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
	ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
	ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
	ctx.closePath();
	ctx.fill();
}
//////////////////////////////////////////////////////////
function killer_draw_state() {

	//cleanup scoreboard
	ctx_k.fillStyle = "rgba(60,60,60,1)";
	ctx_k.fillRect(0,0, board_width,board_height);
	if((blind_rounds_count-current_round_num)<0) {
		var num = 0;
		for (i=0; i<players_max_count; i++) {
			if(players[i].checked) {
	//			ctx_k.fillStyle = "rgba(30,30,30,1)";
	//`			ctx_k.fillRect(5, num*box_height + 5, board_width-10*box_height/30, box_height-3);

				if (player_lifes_killed[i] >= player_lifes[i]) {
					ctx_k.fillStyle = "rgba(60,60,60,1)";
				} else {
					ctx_k.fillStyle = "white";
				}
				ctx_k.font = parseInt(18*box_height/30)+"pt Arial";
				//ctx_k.fillText(player_names[i], 10, i*box_height + 25);
				ctx_k.fillText(players[i].name, 10, num*box_height + 30*box_height/30);

				if (player_lifes_killed[i] >= player_lifes[i]) {
					ctx_k.fillStyle = "rgba(60,60,60,1)";
				} else {
					ctx_k.fillStyle = "yellow";
				}
				ctx_k.font = parseInt(22*box_height/30)+"pt Arial";
				//ctx_k.fillText(player_nums[i], board_width-40, i*box_height + 28);

				ctx_k.fillText(players[i].num, board_width-40, num*box_height + 30*box_height/30);
				 
	/*
				for (j=0; j<player_lifes[i]; j++) {
					if (j < player_lifes_killed[i]) {
					 ctx_k.fillStyle = "black";
					} else {
					 ctx_k.fillStyle = "green";
					}
					draw_life(ctx_k, j*life_width + life_width/1.5, num*box_height + (box_height/4), box_height/10,box_height/2.3, 0);
				}*/
				num++;
			}
		}
	}
	drawPlayersMask();
	drawHurts();
}
//////////////////////////////////////////////////////////
function killer_board_init(width,height,target) {
	if($('#killer_board')) $('#killer_board').remove();
	if($('#hurts')) $('#hurts').remove();
	board_width = width;
	board_height = height-55;
	$('<canvas id="killer_board" width="' + board_width + '" height="' + board_height + '" style="position:relative;vertical-align:top;float:left;">Your browser is currently unsupported canvas</canvas>').appendTo(target);	
	$('<canvas id="hurts" width="' + board_width*2/3 + '" height="' + board_height + '" style="position:relative;vertical-align:top;float:rigtht;">Your browser is currently unsupported canvas</canvas>').appendTo(target);	
	canvas_killer = document.getElementById("killer_board");
	canvas_hurts = document.getElementById("hurts");
	ctx_k = canvas_killer.getContext("2d");
	ctx_h = canvas_hurts.getContext("2d");
	canvas_killer_offset = findPos(canvas_killer);
	ctx_k.globalAlpha = 1.0;
	ctx_h.globalAlpha = 1.0;
	ctx_k.translate(0,0);
	ctx_h.translate(0,0);
	ctx_k.save();

	box_height = (board_height-10) / players_max_count;
	life_width = board_width / (lifes_init_count + extra_lifes_space_count);

	killer_draw_state();
	ctx_k.restore();
}

function killer_game_init() {
	for (i=0; i<players_max_count; i++) {
	 players[i].name = player_names[i];
	 players[i].num = 99;
	 player_lifes[i] = lifes_init_count;
	 player_lifes_killed[i] = 0;
	}
}
//////////////////////////////////////////////////////////
function get_player_by_num(num) {
	for (i=0; i<players_max_count; i++) {
		//if (player_nums[i] == num) {
		if (players[i].num == num && players[i].checked) {
			return (i);
		}
	}
	return (-1);
}
//////////////////////////////////////////////////////////
function get_next_player() {
	prev_player = current_player;

		 do {
				current_player++;
				if (current_player == players_max_count) {
				 current_player = 0;
				 current_round_num++;
				}
				if (player_lifes_killed[current_player] < player_lifes[current_player] && players[current_player].checked) {
					break;
				}
				if (prev_player == current_player) {
					break; // prevent infinity loop
				}
		 } while (true);

	return (current_player);
}
//////////////////////////////////////////////////////////
function undo() {
	if(historyBoard.length > 0) {
		var tmpObj = historyBoard.pop();
//		console.log(tmpObj);
		players = tmpObj.players.slice();
		player_lifes = tmpObj.player_lifes.slice();
		player_lifes_killed = tmpObj.player_lifes_killed.slice();
		current_player = tmpObj.current_player;
		current_dart_num = tmpObj.current_dart_num;
		current_round_num = tmpObj.current_round_num;
		dartsArr = tmpObj.dartsArr.slice();
	//console.log(tmpObj.killsHistory);
	//console.log(killsHistory);
		killsHistory = JSON.parse(JSON.stringify(tmpObj.killsHistory));
	//console.log(killsHistory);
		killer_draw_state();
	} else alert('historyBoard is empty!');
//	 alert('unimplemented feature');
}

function setHistoryBoard() {
	 historyBoard[historyBoard.length] = {
		players					: players.slice(),
		player_lifes_killed		: player_lifes_killed.slice(),
		player_lifes			: player_lifes.slice(),
		current_dart_num		: current_dart_num,
		current_player			: current_player,
		current_round_num		: current_round_num,
		dartsArr				: dartsArr.slice(),
		killsHistory			: JSON.parse(JSON.stringify(killsHistory))
	};
}
//////////////////////////////////////////////////////////
function killer_hook(rad, num,x,y) {
	//log('time, ' + current_game_num + "/" + current_round_num + "/" + current_player + "/" + current_dart_num + "/" + rad + "/" + num);
	if(!gamestarted) {
		if(num>0 && num<21) {
			if(selectedNums.inArray(num)) selectedNums.removeByValue(num);
			else selectedNums[selectedNums.length] = num;
		}
		//console.log(selectedNums);
	} else {
		setHistoryBoard();
		addDart({x:x,y:y},darts_board_height/10);
		//process points
		if (rad >= 0) {
			if (rad >= 2) {
			 var target_player = get_player_by_num(num);
			 var killed_lifes = killed_lifes_by_rad[rad];
			 if (target_player >= 0 && killed_lifes > 0) {
				if (player_lifes_killed[target_player] < player_lifes[target_player]) {
					player_lifes_killed[target_player] += killed_lifes;
					killsHistory[target_player][killsHistory[target_player].length] = {killer:current_player,lifes:killed_lifes};
					if (player_lifes_killed[target_player] > player_lifes[target_player]) {
						player_lifes_killed[target_player] = player_lifes[target_player];
					}
					if (player_lifes_killed[target_player] >= player_lifes[target_player]) {
						//bonus
						player_lifes[current_player] = player_lifes[current_player] + 1;
					}
				}
			 }
			}
			if (rad == 0) {
				//bonus
				player_lifes[current_player] = player_lifes[current_player] + 3;
			}
			if (rad == 1) {
				//bonus
				player_lifes[current_player] = player_lifes[current_player] + 1;
			}
		}

		//process game flow
		if (current_dart_num == dart_num_per_player) {
			current_dart_num = 1;
			current_player = get_next_player();
		} else {
			current_dart_num++;
		}
	}
	killer_draw_state();
}
//////////////////////////////////////////////////////////

function refillPlayers(elem) {
	setHistoryBoard();
	$.each(players, function(i,item) {
		players[i].checked = false;
	});
	$.each($(elem).val(), function(i,item) {
		for(var i=0;i<players.length;i++)
			if(players[i].ind == item) {
				players[i].checked = true;
				return;
			}
	});
	if(!players[current_player].checked)	current_player = get_next_player();
	killer_draw_state();
}

function countCheckedPlayers() {
	var count = 0;
	for(var i=0;i<players.length;i++)
		if(players[i].checked) {
			count++;
		}
	return count;
}

function initPlayers(elem) {
//	console.log($(elem));
	$(elem).empty();
	$.each(players,function(i,item){
		$(elem).append( new Option(item.name,item.ind));
	});
	var vals = new Array();
	for(var i=0; i<players.length; i++) if(players[i].checked) vals[vals.length] = i;
	$(elem).val(vals);
	//console.log($(elem));
}

function drawHurts() {
	if((blind_rounds_count-current_round_num)<0) {
		ctx_h.save();
		var box_height_hurts = 30;
		ctx_h.fillStyle = "rgba(60,60,60,1)";
		ctx_h.fillRect(0,0, board_width,board_height);
		for(var i=0;i<killsHistory[current_player].length;i++) {
			ctx_h.fillStyle = "white";
			ctx_h.font = parseInt(18*box_height/30)+"pt Arial";
			ctx_h.fillText(players[killsHistory[current_player][i].killer].name , 10*box_height/30, i*box_height_hurts + 30*box_height/30);
			ctx_h.fillStyle = "red";
			ctx_h.fillText(killsHistory[current_player][i].lifes, 2/3*board_width-40*box_height/30, i*box_height_hurts + 30*box_height/30);
		}
		ctx_h.restore();
	}
}